<?php

namespace App\Http\Controllers;

/**
 * 
 * 地区控制器
 *
 */
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
use App\Services\BaiduMapService;

class RegionController extends BaseController {

    //获取省市区的树状结构
	/**
	 * @return mixed
	 */
    public function tree(){

        $regions= \App\Models\Region::all();
        $tree = new \App\Libraries\Tree();
        $tree->setTree($regions, 'region_id', 'parent_id', 'region_name');
        return $this->success($tree->getArrayList(1,4));
    }

	// 根据级别获取列表
	public function lists(){

		$parent_id = Input::get('parent_id', '0');
		$query = DB::table('region')->where('parent_id',$parent_id);
		$query = $query->orderBy('region_id')->get();

		return $this->success($query);
	}
    
    // 根据级别编号获取列表
	public function listsByLevel($level) {
		$query = DB::table('region')->where('level',$level);
		$query = $query->select('region.*')->orderBy('region_id')->get();
		return $this->success($query);
	}

	public function getListByLocation(BaiduMapService $mapService){

		$lat =Input::get('lat');
        $lon =Input::get('lon');
		$city =Input::get('city');

		if(!$lat && !$lon && !$city){
			return $this->args_invalid();
		}

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}


		//todo 城市选择
		$data = [
				'cur_city'=>'',
				'districts'=>[],
				'hots'=>[],
				'fulldatas'=>[]
		];


		if($city && $city !='undefined'){
			$data['cur_city']=$city;

		} else {
			$location = $mapService->locationByGPS($lon,$lat);
			$data['cur_city']=$location['city'];
		}

//

		$result = DB::table('region')
				->where('region_name',$data['cur_city'])
				->where('if_show',1)
				->first();
		if(empty($result)){
			//	热门城市
			$hots = DB::table('region')->whereIn('level',[2,3])
					->where('if_show',1)
					->where('is_hot',1)
					->get();

			if($hots){
				foreach($hots as $v){
						$data['hots'][]=['level'=> $v->level==2?'city':'country','city_code'=> $v->province.','.$v->city.','.$v->county,'city_name'=> $v->region_name];
				}
			}

			//获取所有市
			$settles = DB::table('region')->where('level',2)
					->where('if_show',1)
					->get();
			foreach($settles as $settle){
				$firstCharter =$this->_getFirstCharter($settle->region_name);
				$data['fulldatas'][$firstCharter][]=['level'=>'city','city_code'=>$settle->province.','.$settle->city,'city_name'=>$settle->region_name];
				unset($data['fulldatas'][""]);
			}

			return $this->success($data);
		}

		if($result->level == 2){
			$regions = DB::table('region')
					->where('parent_id',$result->region_id)
				    ->where('if_show',1)
					->get();
			$data['districts'][]=['level'=>'city','city_code'=>$result->province.','.$result->city.','.$result->county,'city_name'=>'全部'];
			foreach($regions as $v){
				$v->level='country';
				$data['districts'][]=['level'=> $v->level,'city_code'=> $v->province.','.$v->city.','.$v->county,'city_name'=> $v->region_name];
			}
		}elseif($result->level == 3){
			$result->level='country';
			$data['districts'][]=['level'=> $result->level,'city_code'=> $result->province.','.$result->city.','.$result->county,'city_name'=> $result->region_name];
		}
		$result_toarray = $this->_object_to_array($regions);
		$result_region =array_column($result_toarray,'region_id');
		//	热门城市
		$hots = DB::table('region')->whereIn('level',[2,3])
				->whereNotIn('region_id',$result_region)
				->where('if_show',1)
				->where('is_hot',1)
				->get();

		if($hots){
			foreach($hots as $v){
					if($v->region_name != $data['cur_city']){
						$data['hots'][]=['level'=> $v->level==2?'city':'country','city_code'=> $v->province.','.$v->city.','.$v->county,'city_name'=> $v->region_name];
					}

			}
		}

//		$settlesRes = array();
		//获取所有市
		$settles = DB::table('region')->where('level',2)
				->where('if_show',1)
				->get();
        foreach($settles as $settle){
			$firstCharter =$this->_getFirstCharter($settle->region_name);
			$data['fulldatas'][$firstCharter][]=['level'=>'city','city_code'=>$settle->province.','.$settle->city,'city_name'=>$settle->region_name];
			unset($data['fulldatas'][""]);
		}

		ksort($data['fulldatas']);

		return $this->success($data);

	}

	public function _getFirstCharter($str){
		if(empty($str)){return '';}
		$fchar=ord($str{0});
		if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
		$s1=iconv('UTF-8','gb2312',$str);
		$s2=iconv('gb2312','UTF-8',$s1);
		$s=$s2==$str?$s1:$str;
		$asc=ord($s{0})*256+ord($s{1})-65536;
		if($asc>=-20319&&$asc<=-20284) return 'A';
		if($asc>=-20283&&$asc<=-19776) return 'B';
		if($asc>=-19775&&$asc<=-19219) return 'C';
		if($asc>=-19218&&$asc<=-18711) return 'D';
		if($asc>=-18710&&$asc<=-18527) return 'E';
		if($asc>=-18526&&$asc<=-18240) return 'F';
		if($asc>=-18239&&$asc<=-17923) return 'G';
		if($asc>=-17922&&$asc<=-17418) return 'H';
		if($asc>=-17417&&$asc<=-16475) return 'J';
		if($asc>=-16474&&$asc<=-16213) return 'K';
		if($asc>=-16212&&$asc<=-15641) return 'L';
		if($asc>=-15640&&$asc<=-15166) return 'M';
		if($asc>=-15165&&$asc<=-14923) return 'N';
		if($asc>=-14922&&$asc<=-14915) return 'O';
		if($asc>=-14914&&$asc<=-14631) return 'P';
		if($asc>=-14630&&$asc<=-14150) return 'Q';
		if($asc>=-14149&&$asc<=-14091) return 'R';
		if($asc>=-14090&&$asc<=-13319) return 'S';
		if($asc>=-13318&&$asc<=-12839) return 'T';
		if($asc>=-12838&&$asc<=-12557) return 'W';
		if($asc>=-12556&&$asc<=-11848) return 'X';
		if($asc>=-11847&&$asc<=-11056) return 'Y';
		if($asc>=-11055&&$asc<=-10247) return 'Z';

		//特殊处理
		if($asc == -7703){//衢
			return 'Q';
		}

		return null;
	}
	/**
	 * 对象 转 数组
	 *
	 * @param object $obj 对象
	 * @return array
	 */
	public function _object_to_array($obj) {
		$obj = (array)$obj;
		foreach ($obj as $k => $v) {
			if (gettype($v) == 'resource') {
				return;
			}
			if (gettype($v) == 'object' || gettype($v) == 'array') {
				$obj[$k] = (array)$this->_object_to_array($v);
			}
		}

		return $obj;
	}

}
